import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  CircularProgress,
  IconButton,
  Stack,
  Card,
  CardContent,
  Grid,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Chip,
  LinearProgress,
  Divider
} from '@mui/material';
import { 
  ArrowBack as ArrowBackIcon,
  ExpandMore as ExpandMoreIcon,
  Memory as MemoryIcon,
  Storage as StorageIcon,
  Speed as SpeedIcon,
  Battery90 as BatteryIcon,
  Dns as DnsIcon,
  Router as RouterIcon
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { invoke } from '@tauri-apps/api/core';

const SystemInfoPage = () => {
  const navigate = useNavigate();
  const [systemInfo, setSystemInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchSystemInfo();
  }, []);

  const fetchSystemInfo = async () => {
    try {
      setLoading(true);
      const info = await invoke('get_simplified_system_info');
      console.log('简化系统信息:', info);
      setSystemInfo(info);
      setLoading(false);
    } catch (err) {
      console.error('获取系统信息失败:', err);
      setError(err.toString());
      setLoading(false);
    }
  };

  const formatBytes = (bytes, decimals = 2) => {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
    
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  };
  
  const formatPercentage = (value) => {
    return `${Math.round(value * 100)}%`;
  };

  return (
    <Box sx={{ p: 3 }}>
      <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 3 }}>
        <IconButton 
          onClick={() => navigate('/')}
          sx={{ color: 'text.primary' }}
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4" component="h1">
          系统详情
        </Typography>
      </Stack>

      {loading ? (
        <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
          <CircularProgress />
        </Box>
      ) : error ? (
        <Paper sx={{ p: 3, bgcolor: '#fff3f3' }}>
          <Typography color="error">
            获取系统信息失败: {error}
          </Typography>
        </Paper>
      ) : (
        <Grid container spacing={3}>
          {/* CPU信息 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                  <MemoryIcon color="primary" />
                  <Typography variant="h6">CPU 信息</Typography>
                </Stack>
                <Divider sx={{ mb: 2 }} />
                
                {systemInfo && (
                  <>
                    <Typography variant="subtitle2" gutterBottom>
                      处理器: {systemInfo.cpu_brand || "未知"}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      核心数量: {systemInfo.cpu_count || "未知"}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      CPU使用率:
                    </Typography>
                    <LinearProgress 
                      variant="determinate" 
                      value={Math.min(systemInfo.cpu_usage, 100)} 
                      sx={{ height: 10, borderRadius: 1, mb: 1 }}
                    />
                    <Typography variant="body2" align="right">
                      {Math.min(systemInfo.cpu_usage, 100).toFixed(1)}%
                    </Typography>
                  </>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* 内存信息 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                  <StorageIcon color="primary" />
                  <Typography variant="h6">内存信息</Typography>
                </Stack>
                <Divider sx={{ mb: 2 }} />
                
                {systemInfo && (
                  <>
                    <Typography variant="subtitle2" gutterBottom>
                      总内存: {formatBytes(systemInfo.total_memory || 0)}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      已使用: {formatBytes(systemInfo.used_memory || 0)}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      可用: {formatBytes((systemInfo.total_memory - systemInfo.used_memory) || 0)}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      内存使用率:
                    </Typography>
                    <LinearProgress 
                      variant="determinate" 
                      value={systemInfo.memory_usage_percentage} 
                      sx={{ height: 10, borderRadius: 1, mb: 1 }}
                    />
                    <Typography variant="body2" align="right">
                      {systemInfo.memory_usage_percentage.toFixed(1) + '%'}
                    </Typography>
                  </>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* 系统信息 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                  <DnsIcon color="primary" />
                  <Typography variant="h6">系统信息</Typography>
                </Stack>
                <Divider sx={{ mb: 2 }} />
                
                {systemInfo && (
                  <>
                    <Typography variant="subtitle2" gutterBottom>
                      主机名: {systemInfo.hostname || "未知"}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      操作系统: {systemInfo.system_name || "未知"} {systemInfo.os_version || ""}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      内核版本: {systemInfo.kernel_version || "未知"}
                    </Typography>
                  </>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* 电池信息 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                  <BatteryIcon color="primary" />
                  <Typography variant="h6">电池信息</Typography>
                </Stack>
                <Divider sx={{ mb: 2 }} />
                
                {systemInfo?.battery?.has_battery ? (
                  <>
                    <Typography variant="subtitle2" gutterBottom>
                      制造商: {systemInfo.battery.vendor}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      型号: {systemInfo.battery.model}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      状态: {
                        systemInfo.battery.state === "Full" ? "已充满" :
                        systemInfo.battery.state === "Charging" ? "充电中" :
                        systemInfo.battery.state === "Discharging" ? "放电中" :
                        systemInfo.battery.state
                      }
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      循环次数: {systemInfo.battery.cycle_count}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      电池健康度:
                    </Typography>
                    <LinearProgress 
                      variant="determinate" 
                      value={systemInfo.battery.health} 
                      sx={{ 
                        height: 10, 
                        borderRadius: 1, 
                        mb: 1,
                        '& .MuiLinearProgress-bar': {
                          backgroundColor: 
                            systemInfo.battery.health > 80 ? 'success.main' :
                            systemInfo.battery.health > 50 ? 'warning.main' : 'error.main'
                        }
                      }}
                    />
                    <Typography variant="body2" align="right">
                      {systemInfo.battery.health.toFixed(1)}%
                    </Typography>
                    
                    <Typography variant="body2" gutterBottom sx={{ mt: 2 }}>
                      电池电量:
                    </Typography>
                    <LinearProgress 
                      variant="determinate" 
                      value={systemInfo.battery.percentage} 
                      sx={{ 
                        height: 10, 
                        borderRadius: 1, 
                        mb: 1,
                        '& .MuiLinearProgress-bar': {
                          backgroundColor: 
                            systemInfo.battery.percentage > 60 ? 'success.main' :
                            systemInfo.battery.percentage > 20 ? 'warning.main' : 'error.main'
                        }
                      }}
                    />
                    <Typography variant="body2" align="right">
                      {systemInfo.battery.percentage.toFixed(1)}%
                    </Typography>
                  </>
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    未检测到电池或无电池信息
                  </Typography>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* 磁盘信息 */}
          <Grid item xs={12}>
            <Card>
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                  <SpeedIcon color="primary" />
                  <Typography variant="h6">磁盘信息</Typography>
                </Stack>
                <Divider sx={{ mb: 2 }} />
                
                {systemInfo?.disks && systemInfo.disks.length > 0 ? (
                  <Grid container spacing={2}>
                    {systemInfo.disks.map((disk, index) => (
                      <Grid item xs={12} md={6} key={index}>
                        <Box sx={{ mb: 2, border: '1px solid #e0e0e0', p: 2, borderRadius: 2 }}>
                          <Typography variant="subtitle2" gutterBottom>
                            {disk.name} ({disk.mount_point})
                          </Typography>
                          <Typography variant="body2" gutterBottom>
                            文件系统: {disk.file_system || "未知"}
                          </Typography>
                          <Typography variant="body2" gutterBottom>
                            总空间: {formatBytes(disk.total_space)}
                          </Typography>
                          <Typography variant="body2" gutterBottom>
                            可用空间: {formatBytes(disk.available_space)}
                          </Typography>
                          <Typography variant="body2" gutterBottom>
                            使用率:
                          </Typography>
                          <LinearProgress 
                            variant="determinate" 
                            value={disk.usage_percentage} 
                            sx={{ 
                              height: 10, 
                              borderRadius: 1, 
                              mb: 1,
                              '& .MuiLinearProgress-bar': {
                                backgroundColor: 
                                  disk.usage_percentage > 90 ? 'error.main' :
                                  disk.usage_percentage > 70 ? 'warning.main' : 'success.main'
                              }
                            }}
                          />
                          <Typography variant="body2" align="right">
                            {disk.usage_percentage.toFixed(1)}%
                          </Typography>
                        </Box>
                      </Grid>
                    ))}
                  </Grid>
                ) : (
                  <Typography variant="body2" color="text.secondary">
                    未检测到磁盘信息
                  </Typography>
                )}
              </CardContent>
            </Card>
          </Grid>

          {/* 网络信息 */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                  <RouterIcon color="primary" />
                  <Typography variant="h6">网络信息</Typography>
                </Stack>
                <Divider sx={{ mb: 2 }} />
                
                {systemInfo && (
                  <>
                    <Typography variant="subtitle2" gutterBottom>
                      网络接口:
                    </Typography>
                    {systemInfo.network_interfaces.map((interface_name, index) => (
                      <Typography key={index} variant="body2" gutterBottom>
                        • {interface_name}
                      </Typography>
                    ))}
                    <Typography variant="body2" gutterBottom sx={{ mt: 1 }}>
                      总接收: {formatBytes(systemInfo.total_received || 0)}
                    </Typography>
                    <Typography variant="body2" gutterBottom>
                      总发送: {formatBytes(systemInfo.total_transmitted || 0)}
                    </Typography>
                  </>
                )}
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      )}
    </Box>
  );
};

export default SystemInfoPage; 